<?php

class Db_user_relation extends Model_Db_Core {

	protected  $con       = null;
	protected  $user   = null;
	protected  $user_id   = null;
	protected  $value   = array();

	function __construct(){
	}
	
    public function getUserRelation($user_id) {
	    $con = self::startGDB();
        $con->Select("SELECT u.username, us.* FROM  user u, user_relation ur left join user_session us on us.user_id = ur.user_id WHERE ur.freund_id = ".$user_id." AND u.id = us.user_id and ur.status != 1 ORDER BY us.date DESC");

        $Relations = $con->fetchobject();
        
        foreach ($Relations as $key => $Relation){
            $etime = strtotime("-10 minutes", time());
            $date = date('Y-m-d H:i:s', $etime);
            
            if($date > $Relation->date){	
                $Relations[$key]->Status = 0;
            }else{                	
                $Relations[$key]->Status = 1;
            }
        }
        return $Relations;
	}
   
    public function getRelationInvitation($user_id) {
	    $filter  = array('freund_id'=> $user_id,'status' => "1");
	    $select  = array();
	    
	    parent::getSQLResult(__CLASS__,$filter,$select);
	    $Invitation = parent::result(); 
	    
		return $Invitation;
	}  	
    public function isOpenRelation($user_id) {
        $filter  = array('user_id'=> $user_id,'status' => "1");
        $select  = array();
        
        $getcon = parent::getSQLResult(__CLASS__,$filter,$select);
        $Invitation = parent::result($getcon);
         
        if($Invitation){
            return true;            
        }
        return false;
	}  
	public function accept($user_id,$freund_id) {       
		parent::setInsert(__CLASS__);
		 	 	
		$this->value['user_id'] = $user_id;
		$this->value['freund_id'] = $freund_id;
		$this->value['status'] = 0;
				
	    $status = $this->writeToDb();
	    
	    if($status)
	    {
	        $con = self::startGDB();
            $con->Select('UPDATE user_relation SET status = 0 WHERE user_id = '.$freund_id.' and freund_id = '.$user_id);
	    }    
	    return $status;
	}  
}

?>